const app = getApp();
const reuqestHead = app.globalData.imageRequest;
const commRequest = require("../../request/commRequest.js");
const encryption=require("../../request/encryptionUtils.js");
Page({ 

  /**
   * 页面的初始数据
   */
  data: {
      //判断是否登陆
      isLogin:false,
      userInfo:{},
    requestHead: reuqestHead,
    swiperList:{},
    goodList:[]
   
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getLoginStatus();
    this.getSwiper();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getLoginStatus();
    this.getSwiper();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
   /**
   * 弹窗
   */
  showTest(e){
    wx.showToast({
      title: e,
      icon: 'none'
    })
  },
  /**
   * 登陆状态查询
   */
  getLoginStatus(){
    const userInfo = wx.getStorageSync('userInfo');
    if (userInfo) {
      if ((Date.now() - userInfo.time) > (100 * 10 * 60 * 60 * 2)) {
        this.setData({
          isLogin: false
        })
        wx.removeStorage({
          key: 'userInfo',
          success(res){
            wx.removeStorage({
              key: 'goodList',
            })
            wx.removeStorage({
              key: 'token',
            })
        this.showTest('为了您的账户安全请重新登陆');
          }
        })
      } else {
        let goodList=wx.getStorageSync('goodList');
        this.setData({
          isLogin: true,
          userInfo: userInfo.userId,
          goodList:goodList
        })
      }
     
    } else {
      this.showTest('请先登陆');
      this.setData({
        isLogin: false
      })
    }
  },
  /**
   * 用户登陆
   */
 async login(e){
   let username = e.detail.value.username;
   let password = e.detail.value.password;
   if (!(/^1[3456789]\d{9}$/.test(username))){
     this.showTest('请输入正确手机号');
   }else if(password.length<6){
     this.showTest('请输入六位密码');
   }else{
     let user = { 'username': username, 'password': password };
     const result = encryption.Encrypt(JSON.stringify(user));
     const data = await commRequest.postRequest({ 'url': '/index/login', 'data': { 'data': result } })
     if (data.data.code == "500") {
       this.showTest("账号密码错误");
     } else if (data.data.code == "403") {
       this.showTest("请重新登陆");
     } else {
       let userInfo = JSON.parse(encryption.Decrypt(data.data.data));
      
       this.setData({
         userInfo: userInfo,
         isLogin: true,
         goodList:userInfo.goodsInfoList
       });
       wx.setStorageSync('userInfo', { 'time': Date.now(), 'userId': userInfo });
       wx.setStorageSync('goodList', userInfo.goodsInfoList);

     }
   }
   
 
  },

 
  getSwiper(){
    const swiper = wx.getStorageSync('swiperLogin');
    //判断缓存中是否有轮播图数据，没有则发送请求
    if (!swiper) {
      this.requestSwiper();
    } else {
      //判断缓存有没有过期（时间单位为毫秒）
      //100*10=一秒，如果大于一个小时重新发送请求
      if ((Date.now() - swiper.time) > (100 * 10 * 60 * 60)) {
        this.requestSwiper();
      } else {
        this.setData({
          swiperList: swiper.data
        })
      }
    }
  },
  /**
    * 发送轮播图请求
    */
  async  requestSwiper() {
    const swiperData = await commRequest.postRequest({ url: '/index/getAllSwiperLogin' });
   if(swiperData.data.code==0){
    wx.setStorageSync("swiperLogin", { "time": Date.now(), data: swiperData.data.data })
    this.setData({
      swiperList: swiperData.data.data
    })
   }else{
     this.requestSwiper();
   }
  },
/**
 * 进入设置页面
 */
  setUp() {
    wx.navigateTo({
      url:'../setUp/index'
    })
  },
  /**
   * 进入添加商品页面
   */
  addGoods(){
    wx.navigateTo({
      url: '../addGoods/index',
    })
  },
  /**
   * 删除商品
   */
  deleteGoods(e){
    let that=this;
  wx.showModal({
    title: '提示',
    content: '您确认删除该商品么？',
    success(res) {
      if(res.confirm){
        that.delGoods(e);
      }

    }
  })
  },
  /**
   * 删除商品逻辑
   */
 async delGoods(e){
      let data={'url':"/goodsList/delGoodInfoById","data":{"id":e.target.dataset.id}}
      let result=await commRequest.postRequestHeader(data);
      this.showTest(result.data.message);
     
      if(result.data.code==0){
        this.data.goodList.splice(e.target.dataset.index,1);
        
        this.setData({
          goodList:this.data.goodList
        });
        
        wx.setStorageSync('goodList', this.data.goodList)
      }

  },
  /**
   * 修改商品
   */
  updateGoods(e){
    wx.navigateTo({
      url: '../updateGoods/index?goodId='+e.target.dataset.id,
    })
  }
})

